package chaoyue.study.pool;

import chaoyue.study.ThreadUtils;

import java.util.concurrent.*;

/**
 * 线程池监控
 * 通过ThreadPoolExecutor提供的部分方法可以监控线程池的使用情况
 */
public class MonitorThreadPool extends ThreadPoolExecutor {

    public MonitorThreadPool(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue) {
        super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue);
    }

    /**
     * 线程执行前会调用当前方法
     */
    @Override
    protected void beforeExecute(Thread t, Runnable r) {
        System.out.println("----- beforeExecute -----");
        monitor();
    }

    @Override
    protected void afterExecute(Runnable r, Throwable t) {
        System.out.println("----- afterExecute -----");
        monitor();
    }

    @Override
    protected void terminated() {
        System.out.println("----- terminated -----");
        monitor();
    }

    /**
     * 监控线程池使用情况
     * 都是调用父类的方法获取的
     */
    public void monitor() {
        System.out.println("活动中的线程数：" + getActiveCount());
        System.out.println("当前线程池大小：" + getPoolSize());
        System.out.println("历史最大线程数：" + getLargestPoolSize());
        System.out.println("已提交的任务数：" + getTaskCount());
        System.out.println("已完成的任务数：" + getCompletedTaskCount());
        System.out.println("队列中的任务数：" + getQueue().size());
    }

    public static void main(String[] args) {
        MonitorThreadPool monitorThreadPool = new MonitorThreadPool(1, 3, 0, TimeUnit.SECONDS, new LinkedBlockingQueue<>(10));
        for (int i = 0; i < 10; i++) {
            ThreadUtils.sleepRandom();
            monitorThreadPool.execute(() -> {
                ThreadUtils.sleepRandom();
                System.out.println(Thread.currentThread().getName() + "...");
            });
        }
        ThreadUtils.sleep();
        System.out.println("main...");
        monitorThreadPool.monitor();
        monitorThreadPool.shutdown();
    }
}
